<?php
namespace Action;
use HY\Action;
!defined('HY_PATH') && exit('HY_PATH not defined.');
class Index extends HYBBS {
	public function __construct(){
		parent::__construct();
		//{hook a_index_init}
		$server_ip = $_SERVER["SERVER_ADDR"];
		if($server_ip == "192.168.1.1")
		{
			$this->json($server_ip."为管理ip，请切换加速器网口");
			die;
		}
		if(!IS_LOGIN){
			if(IS_AJAX && IS_POST){
				die($this->json(array('error'=>false,'info'=>'请登录后再操作')));
			}
			else{
				header("location: ". HYBBS_URLA('user','login'));
				die;
			}

		}
	}
	public function Index(){
		/**
		 * 获取服务端IP
		 * @return array|false|mixed|string

		 */

		 

		

		 //phpinfo();

/*
$connection = ssh2_connect('192.168.233.41', 22);
ssh2_auth_password($connection, 'root', 'Euler@7415963');
//执行linux 命令
$stream = ssh2_exec($connection, 'php -v');
stream_set_blocking( $stream, true );
echo (stream_get_contents($stream));
 echo("<br></br>");
$stream = ssh2_exec($connection, 'ls');
stream_set_blocking( $stream, true );
echo (stream_get_contents($stream));
 
*/

		$server_ip = $_SERVER["SERVER_ADDR"];
		if($server_ip == "192.168.1.1")
		{
			$this->json($server_ip."为管理ip，请切换加速器网口");
		}
		$this->view = 'FHL';
		$this->display('index');
	}
	public function process(){
		$key = X('post.key');
		$out = [];
		$re = [];
		exec('tasklist',$out);
		if($key == 'FHL'){
			//$this->json(['tasklist'=>1]);
			foreach($out as $k=>$v){
				if(!strpos($v,'t0.exe')&&strpos($v,'FastExe')===0){
					$tmp = preg_split("/\s+/",$v);
					array_push($re,['name'=>str_replace('FastExe','中转进程',$tmp[0]),'id'=>$tmp[1],'size'=>$tmp[4].$tmp[5]]);
				}
			}

		}elseif($key == 'FTP'){
			foreach($out as $k=>$v){
				if(strpos($v,'FTPServer')===0){
					$tmp = preg_split("/\s+/",$v);
					array_push($re,['name'=>str_replace('FTP','文件同步',$tmp[0]),'id'=>$tmp[1],'size'=>$tmp[4].$tmp[5]]);
				}
			}
		}elseif($key == 'MAIN'){
			foreach($out as $k=>$v){
				if(strpos($v,'ct0.exe')>0&&strpos($v,'FastExe')===0){
					$tmp = preg_split("/\s+/",$v);
					//获取对端连接状态
					$task = S('fhl_ctask')->query('select * from hy_fhl_ctask where taskid = 0')->fetchALL()[0];
					$res = $this->request_post("http://".$task['ip']."/?testConn",[],[]);
					$res = json_decode($res,true);
					$remote_state="80NO";
					if(count($res)>0&&$res["state"]==true){
						$remote_state="80YES";
					}
					array_push($re,['name'=>str_replace('FastExe','高速链路',$tmp[0]),'id'=>$tmp[1],'size'=>$tmp[4].$tmp[5],'state'=>$remote_state]);
				}
				if(strpos($v,'st0.exe')>0&&strpos($v,'FastExe')===0){
					$tmp = preg_split("/\s+/",$v);
					array_push($re,['name'=>str_replace('FastExe','高速链路',$tmp[0]),'id'=>$tmp[1],'size'=>$tmp[4].$tmp[5],'state'=>""]);
				}
			}
		}

		$this->json($re);
		//$res = $this->request_post("http://127.0.0.1/FHL/?testConn",[],[]);
		//$this->json(count(json_decode($res,true)));
	}

	public function resfreshControlCenter(){
		$rs =  M("Sysinfo")->execCmd('/usr/bin/netstat -antp | grep FHLcontrol');
		$rs = explode("\n",trim($rs));
		$rs = preg_replace("/\s{2,}/",' ',$rs);

		$ccInfo = [];
		foreach($rs as $k=>$v){
			$v = explode(" ",$v);
			if($v[0] == "tcp"){
				array_push($ccInfo, [
								"item_XY"=>$v[0],
								"name"=>$v[6],
								"portL"=>explode(":",$v[3])[1]
						]);
			}
		}
		$this->json([
			"state"=>true,
			"data"=>$ccInfo
		]);
	}
	public function restartControlCenter(){
		$rs =  M("Sysinfo")->execCmd('/usr/bin/netstat -antp | grep FHLcontrol');
		$rs = explode("\n",trim($rs));
		$rs = preg_replace("/\s{2,}/",' ',$rs);


		foreach($rs as $k=>$v){
			$v = explode(" ",$v);
			if($v[0] == "tcp"){
				//$this->json($v);
				M("Sysinfo")->execCmd('kill '.explode("/",$v[6])[0]);
				//$v[6]
			}
		}

		$re = M("Sysinfo")->execCmd("nohup ".INDEX_PATH."/FHL/FHLcontrol >/dev/null 2>&1 &");
		$this->json([
				"state"=>true,
				"info"=>$re
		]);
	}


	private function request_post($url, $post_data,$headers){
		// header传送格式
		// $headers = array(
		//     "token:1111111111111",
		//     "over_time:22222222222",
		// );
		//初始化
		$curl = curl_init();
		//设置抓取的url
		curl_setopt($curl, CURLOPT_URL, $url);
		//设置头文件的信息作为数据流输出
		curl_setopt($curl, CURLOPT_HEADER, false);
		//设置获取的信息以文件流的形式返回，而不是直接输出。
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		//设置post方式提交
		curl_setopt($curl, CURLOPT_POST, true);
		// 设置post请求参数
		curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
		// 添加头信息
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		// CURLINFO_HEADER_OUT选项可以拿到请求头信息
		curl_setopt($curl, CURLINFO_HEADER_OUT, true);
		// 不验证SSL
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		//执行命令
		$data = curl_exec($curl);
		// 打印请求头信息
//        echo curl_getinfo($curl, CURLINFO_HEADER_OUT);
		//关闭URL请求
		curl_close($curl);
		//显示获得的数据
		return $data;
	}

	private function request_get($url){
		// header传送格式
		$headers = array(
				"token:1111111111111",
				"over_time:22222222222",
		);
		// 初始化
		$curl = curl_init();
		// 设置url路径
		curl_setopt($curl, CURLOPT_URL, $url);
		// 将 curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true) ;
		// 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
		curl_setopt($curl, CURLOPT_BINARYTRANSFER, true) ;
		// 添加头信息
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		// CURLINFO_HEADER_OUT选项可以拿到请求头信息
		curl_setopt($curl, CURLINFO_HEADER_OUT, true);
		// 不验证SSL
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		// 执行
		$data = curl_exec($curl);
		// 打印请求头信息
		//        echo curl_getinfo($curl, CURLINFO_HEADER_OUT);
		// 关闭连接
		curl_close($curl);
		// 返回数据
		return $data;
	}
	public function getFileChain(){
		$PREChain = M("Sysinfo")->execCmd('/usr/sbin/iptables -t nat -L PREROUTING |grep -E "(DNAT)"');
		$PREChain = explode("\n",trim($PREChain,"\n"));
		$POSTChain = M("Sysinfo")->execCmd('/usr/sbin/iptables -t nat -L POSTROUTING |grep -E "(SNAT)"');
		$POSTChain = explode("\n",trim($POSTChain,"\n"));
		$res = [];
		foreach($PREChain as $k=>$v){
			$v = preg_replace("/\s{2,}/",' ',$v);
			$vv = preg_replace("/\s{2,}/",' ',$POSTChain[$k]);

			array_push($res,[
				"from"=>filter_var(explode(" ",$vv)[3],FILTER_VALIDATE_IP)?explode(" ",$vv)[3]:"-.-.-.1",
					"to"=>explode(" ",$v)[7],

			]);
		}
		$this->json([
			"state"=>true,
			"info"=>$res
		]);

	}
	public function getProxy(){
		//获取FHLproxy运行情况
        $Proxy = M("Sysinfo")->execCmd(' ps -elf |grep \'FHLproxy\'|awk \'{print $4 " " $15$16}\'');
        $Proxy = explode("\n",trim($Proxy));
        $res = [];
        foreach($Proxy as $k=>$v){
            $v = explode(" ",$v);
            //$this->json("proxy".$task['type']);
            if(strpos($v[1],"FHL/FHLproxy")){
                array_push($res,[
                    "ID"=>$v[0],
                    "name"=>$v[1],
                ]);
            }
        }
		//获取FHLsocket5运行情况
        $Proxy = M("Sysinfo")->execCmd(' ps -elf |grep \'FHLsocket5\'|awk \'{print $4 " " $15$16}\'');
        $Proxy = explode("\n",trim($Proxy));
       
        foreach($Proxy as $k=>$v){
            $v = explode(" ",$v);
            //$this->json("proxy".$task['type']);
            if(strpos($v[1],"FHL/FHLsocket5")){
                array_push($res,[
                    "ID"=>$v[0],
                    "name"=>$v[1],
                ]);
            }
        }

       $this->json([
           "state"=>true,
           "info"=>$res
       ]);
    }
    public function getSysInfo(){
		$this->json([
			"state"=>true,
			"info"=>M("Sysinfo")->getSysInfo()
		]);

    }



}
